import type { FC } from 'react';
import React, { useState } from 'react';
import { LikeOutlined, MessageOutlined, StarOutlined } from '@ant-design/icons';
import { ModalForm, ProFormDigit } from '@ant-design/pro-form';
import { Avatar, Card, Input, List, Radio, Space, message } from 'antd';
import { useEffect } from 'react';
import { history } from 'umi';

import { PageContainer } from '@ant-design/pro-layout';
import type { RadioChangeEvent } from 'antd';
import moment from 'moment';
import { queryFakeList, updateShareAndView, updateShowStatus, queryCurrent } from './service';
import type { BasicListItemDataType } from './data.d';
import styles from './style.less';

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { Search } = Input;

const Info: FC<{
    title: React.ReactNode;
    value: React.ReactNode;
    bordered?: boolean;
}> = ({ title, value, bordered }) => (
    <div className={styles.headerInfo}>
        <span>{title}</span>
        <p>{value}</p>
        {bordered && <em />}
    </div>
);

export const BasicList: FC = () => {
    const [modalVisible, handleModalVisible] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState<Object>({});
    const [list, setList] = useState<Array>([]);
    const [total, setTotal] = useState<number>(0);
    const [pageNum, setPageNum] = useState<number>(1);
    const [param, setParam] = useState<Object>({
        pageNum: 1,
        pageSize: 10,
        hospitalId: sessionStorage.getItem(`hosiptaAuthlId`),
    });
    console.log('sessionStorage.getItem(`hosiptaAuthlId`)', sessionStorage.getItem(`hosiptaAuthlId`));
    let currentUser = JSON.parse(sessionStorage.getItem('currentUser'));

    // const { data: currentUser, loading } = useRequest(() => {
    //   return queryCurrent();
    // });

    const initList = async (param: object) => {
        try {
            const response = await queryFakeList(param);
            if (response.code == 200) {
                console.log('respose', response);
                setList(response.data.records);
                setTotal(response.data.total);
            } else {
                message.error('获取数据失败!');
            }
        } catch (error) {
            message.error('获取数据失败' + error);
        }
    };

    const showItem = async (postData: object) => {
        const hide = message.loading('正在处理');
        try {
            const response = await updateShowStatus(postData);
            if (response.code == 200) {
                message.success('处理成功,即将刷新');
                initList(param);
            } else {
                message.error('处理失败!');
            }
            hide();
            return true;
        } catch (error) {
            hide();
            message.error('处理失败');
            return false;
        }
    };

    const ListContent = ({
        data: { publishTime, status, baseArticleId },
    }: {
        data: BasicListItemDataType;
    }) => (
        <div className={styles.listContent}>
            <div className={styles.listContentItem}>
                <p>{moment(publishTime).format('YYYY-MM-DD HH:mm')}</p>
                <Space>
                    <a
                        key="comment"
                        onClick={(e) => {
                            e.preventDefault();
                            history.push('/content/doctor-creation-detail?id=' + baseArticleId);
                        }}
                    >
                        查看
                    </a>
                    <a
                        key="hide"
                        onClick={(e) => {
                            e.preventDefault();
                            // showEditModal(item);
                            let postData = {
                                baseArticleId: baseArticleId, //文章id
                                status: status == 0 ? 1 : 0, //状态 1 显示 0 不显示
                            };

                            showItem(postData);
                        }}
                    >
                        {status == 1 ? '对外隐藏' : '对外显示'}
                    </a>
                    {currentUser ? (
                        currentUser.adminType == 1 || currentUser.adminType == 0 ? (
                            <a
                                key="update"
                                onClick={(e) => {
                                    e.preventDefault();
                                    // showEditModal(item);
                                    let currentRow = { baseArticleId: baseArticleId };
                                    setCurrentRow(currentRow);
                                    handleModalVisible(true);
                                }}
                            >
                                更新数据
                            </a>
                        ) : null
                    ) : null}
                </Space>
            </div>
        </div>
    );

    // const {
    //   data: listData,
    //   loading,
    //   mutate,
    // } = useRequest(() => {
    //   return queryFakeList({
    //     pageNum: 1,
    //     pageSize: 1000,
    //   });
    // });

    //console.log('data', listData);
    //const list = listData?.records || [];

    // const paginationProps = {
    //   showSizeChanger: true,
    //   showQuickJumper: true,
    //   pageSize: 10,
    //   total: listData?.total || 0,
    // };

    const IconText = ({ icon, text }: { icon: React.FC; text: string }) => (
        <Space>
            {React.createElement(icon)}
            {text}
        </Space>
    );

    const onChange = ({ target: { value } }: RadioChangeEvent) => {
        console.log('radio1 checked', value);
        let paramNew = {
            pageNum: 1,
            pageSize: 10,
            hospitalId: sessionStorage.getItem(`hosiptaAuthlId`),
        };
        if (value == 'all') {
        } else {
            paramNew.channel = value;
        }
        setParam(paramNew);
        initList(paramNew);
    };

    const onSearch = (value: string) => {
        param.articleTitle = value;
        param.pageNum = 1;
        setParam(param);
        initList(param);
    };

    const extraContent = (
        <div className={styles.extraContent}>
            <RadioGroup defaultValue="all" onChange={onChange}>
                <RadioButton value="all">全部</RadioButton>
                <RadioButton value="130060">科普文章</RadioButton>
                <RadioButton value="130100">病例交流</RadioButton>
            </RadioGroup>
            <Search className={styles.extraContentSearch} placeholder="请输入" onSearch={onSearch} />
        </div>
    );

    const renderTitle = ({ item }) => (
        <div className={styles.titleContent}>
            <span>
                {item.deptName} | {item.doctorName}
            </span>
            <div>{item.articleTitle}</div>
            <div className={styles.contentType}>{item.channelName}</div>
            <Space>
                <IconText icon={StarOutlined} text={item.viewNum} key="list-vertical-star-o" />
                <IconText icon={LikeOutlined} text={item.likeNum} key="list-vertical-like-o" />
                <IconText icon={MessageOutlined} text={item.commentNum} key="list-vertical-message" />
            </Space>
        </div>
    );

    const handleShareAndView = async (record: API.RuleListItem[]) => {
        const hide = message.loading('正在处理');
        try {
            const response = await updateShareAndView(record);
            if (response.code == 200) {
                message.success('处理成功,即将刷新');
            } else {
                message.error('处理失败!');
            }
            hide();
            return true;
        } catch (error) {
            hide();
            message.error('处理失败');
            return false;
        }
    };

    useEffect(() => {
        initList(param);
    }, []);
    return (
        <div>
            <PageContainer>
                {modalVisible ? (
                    <ModalForm
                        title={'更新数据'}
                        width="500px"
                        layout="horizontal"
                        visible={modalVisible}
                        onVisibleChange={handleModalVisible}
                        onFinish={async (value) => {
                            // value.viewNum = type;
                            // value.likeNum = type;
                            value.baseArticleId = currentRow.baseArticleId;
                            console.log('value', value);
                            let success = await handleShareAndView(value as Object);
                            if (success) {
                                handleModalVisible(false);
                                // let param = {
                                //   pageNum: pageNum,
                                //   pageSize: 10,
                                // };
                                // param.pageNum=pageNum;
                                initList(param);
                            }
                        }}
                    >
                        <ProFormDigit
                            rules={[
                                {
                                    required: true,
                                    message: '请输入',
                                },
                            ]}
                            label="阅读量"
                            width="md"
                            min={1}
                            name="viewNum"
                        />
                        <ProFormDigit
                            rules={[
                                {
                                    required: true,
                                    message: '请输入',
                                },
                            ]}
                            label="点赞量"
                            width="md"
                            min={1}
                            name="likeNum"
                        />
                    </ModalForm>
                ) : null}
                <div className={styles.standardList}>
                    <Card
                        className={styles.listCard}
                        bordered={false}
                        title=""
                        style={{ marginTop: 24 }}
                        bodyStyle={{ padding: '0 32px 40px 32px' }}
                        extra={extraContent}
                    >
                        <List
                            // itemLayout="vertical"
                            size="large"
                            rowKey="id"
                            // loading={loading}
                            // pagination={paginationProps}
                            pagination={{
                                onChange: (page) => {
                                    console.log(page);
                                    setPageNum(page);
                                    param.pageNum = page;
                                    setParam(param);
                                    initList(param);
                                },
                                showSizeChanger: true,
                                showQuickJumper: true,
                                pageSize: 10,
                                total: total,
                            }}
                            dataSource={list}
                            renderItem={(item) => (
                                <List.Item
                                // actions={[

                                // ]}
                                >
                                    <List.Item.Meta
                                        avatar={
                                            <Avatar
                                                src={'http://oss.yizuoyiyou.com.cn' + item.doctorHeadPic}
                                                shape="square"
                                                size="large"
                                            />
                                        }
                                        title={renderTitle({ item })}
                                    // description={renderDescription({ item })}
                                    />
                                    <ListContent data={item} />
                                </List.Item>
                            )}
                        />
                    </Card>
                </div>
            </PageContainer>
        </div>
    );
};

export default BasicList;
